package com.atguigu.flink.wordcount;

import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.Arrays;


/**
 * Created by 黄凯 on 2023/6/11 0011 20:17
 *
 * @author 黄凯
 * 永远相信美好的事情总会发生.
 */
public class Flink05_LambdaWordCount {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //美/ˈpærəlelɪzəm/
        env.setParallelism(1);

//        env.setRuntimeMode(RuntimeExecutionMode.AUTOMATIC);
        env.setRuntimeMode(RuntimeExecutionMode.STREAMING);

        DataStreamSource<String> ds = env.readTextFile("input/words.txt");
//        DataStreamSource<String> ds = env.socketTextStream("127.0.0.1", 8888);

        SingleOutputStreamOperator<Tuple2<String, Integer>> flatMapDs = ds.flatMap(

                (line, out) -> Arrays.stream(line.split(" "))
                        .forEach(word -> out.collect(Tuple2.of(word, 1))),

                Types.TUPLE(Types.STRING, Types.INT)
        );

        KeyedStream<Tuple2<String, Integer>, String> keyByDs = flatMapDs.keyBy(tuple2 -> tuple2.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> sumDs = keyByDs.sum(1);

        sumDs.print();

        env.execute();

    }

}
